package com.jyskkebank.android.toggl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import com.jyskebank.android.toggl.domain.Project;
import com.jyskebank.android.toggl.domain.TimeEntry;

public class TaskActivity extends Activity implements View.OnClickListener {
	Context mContext;
	TimeEntry selectedTimeEntry;

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.taskmenu, menu);
		return true;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task);

		TextView projectTask = (TextView) findViewById(R.id.task_project);
		projectTask.setOnClickListener(this);

		TextView dateTask = (TextView) findViewById(R.id.task_date);
		dateTask.setOnClickListener(this);

		TextView timeTask = (TextView) findViewById(R.id.task_timer_duration);
		timeTask.setOnClickListener(this);

		Bundle extras = getIntent().getExtras();

		String apiToken = extras.getString("apiToken");

		this.selectedTimeEntry = (TimeEntry) extras
				.getSerializable("timeEntry");

		AutoCompleteTextView desc = (AutoCompleteTextView) findViewById(R.id.task_description);
		if (this.selectedTimeEntry != null) {
			desc.setText(selectedTimeEntry.getDescription());
			projectTask.setText(selectedTimeEntry.getProject().getName());
			String startTime = selectedTimeEntry.getStartTime();
			System.out.println(" startTime : "+ startTime);
			String date = startTime.toString();
			String year = date.substring(0, date.indexOf("-"));
			String month = date.substring(date.indexOf("-") + 1,
					date.lastIndexOf("-"));
			String day = date.substring(date.lastIndexOf("-") + 1,
					date.length());
			startTime = day + "-" + month + "-" + year;
			
			CheckBox billableBox = (CheckBox) findViewById(R.id.task_billable_cb);
			billableBox.setChecked(selectedTimeEntry.isBillabe());

			TextView projectId = (TextView) findViewById(R.id.task_project_id);
			projectId.setText(String.valueOf(selectedTimeEntry.getProject().getId()));

			dateTask.setText(startTime);
			int hour = selectedTimeEntry.getDuration() / 3600;
			int minutes = (selectedTimeEntry.getDuration() % 3600) / 60;
			timeTask.setText(hour + ":" + minutes + " (hh:mi)");
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.task_project:
			showProjectDialog();
			break;
		case R.id.task_date:
			showDatePicker();
			break;
		case R.id.task_timer_duration:
			showTimePicker();
			break;
		}
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.saveTask:
			setTaskListContent();
			break;
		case R.id.cancelTask:
			goToTaskListPage();
			break;
		case R.id.deleteTask:
			TogglUtil togglUtil = new TogglUtil();
			String apiToken = getIntent().getExtras().getString("apiToken");
			togglUtil.deleteTimeEntry(apiToken, String.valueOf(this.selectedTimeEntry.getId()));
			goToTaskListPage();
			return true;
		}
		return false;
	}

	private void goToTaskListPage() {
		Intent intent = new Intent(this, TaskListActivity.class);
		intent.putExtra("apiToken",
				getIntent().getExtras().getString("apiToken"));
		intent.putExtra("workspaceId",
				getIntent().getExtras().getString("workspaceId"));
		startActivity(intent);
		//startActivity(intent);
	}

	private void setTaskListContent() {
		Bundle extras = getIntent().getExtras();
		TimeEntry selectedTimeEntry = (TimeEntry) extras
				.getSerializable("timeEntry");
		
		String apiToken = getIntent().getExtras().getString("apiToken");
		System.out.println("API TOKEN TASK >>>> " + apiToken);
		String jsonString = null;
		TimeEntry timeEntry = new TimeEntry();

		AutoCompleteTextView desc = (AutoCompleteTextView) findViewById(R.id.task_description);
		timeEntry.setDescription(desc.getText().toString());

		TextView projectTask = (TextView) findViewById(R.id.task_project);
		Project project = new Project();
		project.setName(projectTask.getText().toString());
		TextView projectId = (TextView) findViewById(R.id.task_project_id);
		project.setId(Long.valueOf(projectId.getText().toString()));
		timeEntry.setProject(project);

		TextView dateTask = (TextView) findViewById(R.id.task_date);
		System.out.println("dateTask :" + dateTask.getText().toString());
		String date = dateTask.getText().toString();
		String day = date.substring(0, date.indexOf("-"));
		String month = date.substring(date.indexOf("-") + 1,
				date.lastIndexOf("-"));
		String year = date.substring(date.lastIndexOf("-") + 1,
				date.lastIndexOf("-") + 5);
		date = year + "-" + month + "-" + day;
		System.out.println("date : " + date);
		/*timeEntry.setStartTime("2012-02-02T15:58:00+05:30");
		timeEntry.setStopTime("2012-02-02T16:28:00+05:30");*/

		TextView timeTask = (TextView) findViewById(R.id.task_timer_duration);
		String duration = timeTask.getText().toString();
		timeEntry.setDuration((Integer.parseInt(duration.substring(0,
				duration.indexOf(":"))) * 3600)
				+ Integer.parseInt(duration.substring(
						duration.indexOf(":") + 1, duration.indexOf("(") - 1))
				* 60);
		
		CheckBox checkBox = (CheckBox) findViewById(R.id.task_billable_cb);
		timeEntry.setBillabe(checkBox.isChecked());
		timeEntry.setWorkspaceId(Integer.parseInt(getIntent().getExtras()
				.getString("workspaceId")));

		Long id = Long.valueOf(0);
		if (selectedTimeEntry != null) {
			id = selectedTimeEntry.getId();
		}
		timeEntry = setTime(timeEntry,day,month,year,timeEntry.getDuration());
		
		jsonString = timeEntry.toJSONArray();

		/*
		 * jsonString = "{\"time_entry\":{" + "\"tag_names\":[]" +
		 * ",\"billable\":true" + ",\"workspace\":{\"id\":33379}" +
		 * ",\"description\":\"Neeraj test entry\"" +
		 * ",\"project\":{\"id\":875090}" + ",\"duration\":1800" +
		 * ",\"start\":\"2012-02-02T15:58:00+05:30\"" +
		 * ",\"stop\":\"2012-02-02T15:58:00+05:30\"" +
		 * ",\"created_with\":\"JBT\"" + "}}";
		 */

		TogglUtil util = new TogglUtil();
		String response = util.updateTimeEntry(apiToken, id, jsonString);
		Intent intent = new Intent(this, TaskListActivity.class);
		intent.putExtra("apiToken", apiToken);
		String workspaceId = getIntent().getExtras().getString("workspaceId");
		intent.putExtra("workspaceId", workspaceId);
		startActivity(intent);
	}

	private void showProjectDialog() {
		String apiToken = getIntent().getExtras().getString("apiToken");
		TogglService togglService = new TogglService();
		final List<Project> projectList = togglService.getProjectList(apiToken);
		final CharSequence[] projects = new CharSequence[projectList.size()];
		int i = 0;
		for (Project project : projectList) {
			projects[i] = project.getClientProjectName();
			i++;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pick a project");
		builder.setSingleChoiceItems(projects, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int i) {
						TextView projectTask = (TextView) findViewById(R.id.task_project);
						projectTask.setText(projects[i]);
						for (Project project : projectList) {
							if (project.getClientProjectName().equals(
									projects[i])) {
								TextView projectId = (TextView) findViewById(R.id.task_project_id);
								projectId.setText(String.valueOf(project
										.getId()));
								break;
							}
						}
						dialog.cancel();
					}
				});
		builder.show();
	}

	private void showDatePicker() {
		final Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH);
		int mDay = c.get(Calendar.DAY_OF_MONTH);
		new DatePickerDialog(this, new OnDateSetListener() {
			TextView mDateDisplay = (TextView) findViewById(R.id.task_date);

			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				this.mDateDisplay.setText(new StringBuilder()
						.append(dayOfMonth).append("-").append(monthOfYear + 1)
						.append("-").append(year).append(" "));

			}
		}, mYear, mMonth, mDay).show();
	}

	private void showTimePicker() {
		final Calendar c = Calendar.getInstance();
		TimePickerDialog dialog = new TimePickerDialog(this,
				new OnTimeSetListener() {
					TextView timerDuration = (TextView) findViewById(R.id.task_timer_duration);

					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						this.timerDuration.setText(new StringBuilder()
								.append(hourOfDay).append(":").append(minute)
								.append(" (hh:mi)"));
					}
				}, 00, 00, true);
		dialog.show();
	}
	
	 private TimeEntry setTime(TimeEntry timeEntry,String day,String month,String year, long duration) {
		  Calendar now = Calendar.getInstance();
		  SimpleDateFormat dateFormat = new SimpleDateFormat(
		    "yyyy-MM-dd'T'HH:mm:ss'+05:30'");
		  
		  now.set(Calendar.DATE, Integer.parseInt(day));
		  now.set(Calendar.MONTH, Integer.parseInt(month)-1);
		  now.set(Calendar.YEAR, Integer.parseInt(year));
		  System.out.println(" dateFormat.format(now.getTime()) :" + dateFormat.format(now.getTime()));
		  timeEntry.setStartTime(dateFormat.format(now.getTime()));
		  int hours = (int) ( duration/ 3600);
		  int remainder = (int) (duration % 3600);
		  int minutes = remainder / 60;
		  int seconds = remainder % 60;
		  
		  now.add(Calendar.HOUR, hours);
		  now.add(Calendar.MINUTE, minutes);
		  now.add(Calendar.SECOND, seconds);
		  timeEntry.setStopTime(dateFormat.format(now.getTime()));
		  return timeEntry;
		 }
}
